#include <cstdio>
#include <cstring>

#define _WIN32_WINNT 0x0501

#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/format.hpp>

using boost::asio::ip::udp;
using namespace std;


bool getquery_p(char ip[], int port, int &players, int &maxplayers)
{
	try
	{
		boost::asio::io_service io_service;

		udp::resolver resolver_ob(io_service);
		udp::resolver::query query_ob(udp::v4(), ip, boost::io::str(boost::format("%1%") % port));


		udp::endpoint receiver_endpoint = *resolver_ob.resolve(query_ob);

		udp::socket socket(io_service);
		socket.open(udp::v4());

		int ipunformatted[4];
		sscanf_s(ip, "%i.%i.%i.%i", &ipunformatted[0], &ipunformatted[1],&ipunformatted[2],&ipunformatted[3]);

		boost::array<char, 12> send_buf  =
		{
			'S', 'A', 'M', 'P',
			(char) ipunformatted[0],
			(char) ipunformatted[1],
			(char) ipunformatted[2],
			(char) ipunformatted[3],
			(char) port & 0xff,
			(char) (port >> 8) & 0xff,
			'i', '\0'
		};
		socket.send_to(boost::asio::buffer(send_buf), receiver_endpoint);



		boost::array<char, 32> recv_buf;
		udp::endpoint sender_endpoint;
		size_t len = socket.receive_from(
			boost::asio::buffer(recv_buf), sender_endpoint);

		players = (recv_buf[12]) + (recv_buf[13] << 8);
		maxplayers =(recv_buf[14])+ (recv_buf[15] << 8);
	}
	catch(exception&)
	{
		players = -1;
		maxplayers = -1;
		return false;
	}
	catch(...)
	{
		players = -1;
		maxplayers = -2;
		return false;
	}

	return true;
}



